package com.atguigu.day03;

import com.atguigu.utils.IntegerSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

// ValueState：值状态变量
public class Example10 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntegerStatistic>() {
                    // 声明状态变量
                    // 每个key维护自己的状态变量
                    // 状态变量是一个单例，只能初始化一次
                    private ValueState<IntegerStatistic> accumulator;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        // 初始化了一个空累加器
                        accumulator = getRuntimeContext().getState(
                                // 字符串acc表示状态变量在状态后端里的名字
                                new ValueStateDescriptor<IntegerStatistic>("acc", Types.POJO(IntegerStatistic.class))
                        );
                    }

                    @Override
                    public void processElement(Integer value, Context ctx, Collector<IntegerStatistic> out) throws Exception {
                        // .value()用来读取值状态变量中的值
                        if (accumulator.value() == null) {
                            // 第一条数据到达
                            // .update更新状态变量
                            accumulator.update(
                                    new IntegerStatistic(
                                            value,
                                            value,
                                            value,
                                            1,
                                            value
                                    )
                            );
                        } else {
                            // 输入数据和累加器进行聚合并更新累加器
                            IntegerStatistic tmp = accumulator.value();
                            IntegerStatistic newAcc = new IntegerStatistic(
                                    Math.max(value, tmp.max),
                                    Math.min(value, tmp.min),
                                    value + tmp.sum,
                                    tmp.count + 1,
                                    (value + tmp.sum) / (tmp.count + 1)
                            );
                            accumulator.update(newAcc);
                        }

                        out.collect(accumulator.value());
                    }
                })
                .print();

        env.execute();
    }

    public static class IntegerStatistic {
        public Integer max;
        public Integer min;
        public Integer sum;
        public Integer count;
        public Integer avg;

        public IntegerStatistic() {
        }

        public IntegerStatistic(Integer max, Integer min, Integer sum, Integer count, Integer avg) {
            this.max = max;
            this.min = min;
            this.sum = sum;
            this.count = count;
            this.avg = avg;
        }

        @Override
        public String toString() {
            return "IntegerStatistic{" +
                    "max=" + max +
                    ", min=" + min +
                    ", sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    '}';
        }
    }
}
